package com.xzc.web;

import com.xzc.utils.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 徐州城
 * @version 1.0
 */
public class CookieServlet extends BaseServlet {

    protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、创建Cookie对象
        Cookie cookie = new Cookie("key1","value1");
        Cookie cookie2 = new Cookie("key2","value2");
        Cookie cookie3 = new Cookie("key3","value3");
        //2、通知客户端保存Cookie
        resp.addCookie(cookie);
        resp.addCookie(cookie2);
        resp.addCookie(cookie3);

        resp.getWriter().write("Cookie创建成功！");
    }

    protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();

        for (Cookie cookie : cookies) {
            //getName()：返回Cookie的 key/名称
            //getValue()：返回Cookie的value值
            resp.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "] <br/>");
        }

        Cookie iWantCookie = CookieUtils.findCookie("key1",cookies);
        //如果不等于null，说明有值，也就是找到了需要的cookie
        if (iWantCookie != null){
            resp.getWriter().write("找到了需要的Cookie");
        }
    }

    protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        //方式一：
//        //1、先创建一个要修改的同名（指的就是 key）的 Cookie 对象
//        //2、在构造器，同时赋于新的 Cookie 值。
//        Cookie cookie = new Cookie("key1","newValue1");
//        //3、调用 response.addCookie(Cookie); 通知客户端，保存修改
//        resp.addCookie(cookie);
//        resp.getWriter().write("key1的Cookie已经修改好");
//

        //1、先查找到需要修改的 Cookie 对象
        Cookie cookie = CookieUtils.findCookie("key2",req.getCookies());
        if (cookie != null){
            //2、调用 setValue()方法赋于新的 Cookie 值。
            cookie.setValue("newValue2");
            //3、调用 response.addCookie()通知客户端保存修改
            resp.addCookie(cookie);
        }
    }

    protected void defaultLift(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("defaultLife","defaultLife");
        cookie.setMaxAge(-1);//设置存活时间
        resp.addCookie(cookie);
    }

    protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("path1", "path1");
        //getContextPath()：得到工程路径
        cookie.setPath(req.getContextPath() + "/abc"); //表示 /工程路径/abc
        resp.addCookie(cookie);
        resp.getWriter().write("创建了带有Path路径的Cookie");
    }
}
